package com.c3w.synchro.common.dao;

import com.c3w.synchro.common.bean.Bean;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * User: P.Lalonde
 * Date: 09/02/13
 */
public class BeanDao<T extends Bean> implements Dao<Long, T> {
    @PersistenceContext
    protected EntityManager em;

    private final Class<T> beanClazz;

    public BeanDao(Class<T> beanClazz) {
        this.beanClazz = beanClazz;
    }

    @Override
    public void persist(T entity) {
        em.persist(entity);
    }

    @Override
    public void remove(T entity) {
        em.remove(entity);
    }

    @Override
    public T merge(T entity) {
        return em.merge(entity);
    }

    @Override
    public void refresh(T entity) {
        em.refresh(entity);
    }

    @Override
    public T findById(Long id) {
        return em.find(beanClazz, id);
    }

    @Override
    public List<T> findAll() {
        String classSimpleName = beanClazz.getSimpleName();
        Query query = em.createQuery("SELECT h FROM " + classSimpleName + " h");
        return query.getResultList();
    }
}
